/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { useHistory, history, useDispatch, useLocation, useSelector } from 'umi';
import type { History } from 'umi';
import { useEffect, useRef, useState } from 'react';
import type { ConnectState } from '@/models/connect';
import { expandRoutes } from '../admin/menu';
import { getStorage, setStorage } from '../utils';

const PAGE_TABS = 'PAGE_TABS';

/**
 * @description 有子页面的tab中展示需要兼容
 * 例子 ：父页面：/f/wechat/mini；
 *       子页面：/f/wechat/mini/admin
 */
export function fixPathnameHasParent(pathname: string) {
  if (!pathname) return pathname;
  const pathnameList = pathname.split('/');
  const pathsMax = 4;
  if (pathnameList.length > pathsMax) {
    return pathnameList.slice(0, pathsMax).join('/');
  }
  return pathname;
}

export interface TabItem {
  name: string;
  pathname: string;
}

type Tabs = TabItem[];

export type UpdateTabsType = 'remove' | 'change';

type UpdateTabs = (type: UpdateTabsType, key: string) => TabItem;

/**
 *
 * @description 记录tab
 * @param routes
 * @returns
 */
export function useRecordTab(routes: []): [Tabs, string, UpdateTabs] {
  const storageTabs: Tabs = getStorage(PAGE_TABS) || [];
  const [tabs, setTabs] = useState<Tabs>(storageTabs);
  const [activeKey, setActiveKey] = useState<string>('');
  const { location } = useHistory() as History;
  const { pathname } = location || {};
  const actionRef = useRef<{ tabs: Tabs }>({ tabs: storageTabs });
  const dispatch = useDispatch();
  const routesFormat = expandRoutes(routes);

  /**
   *
   * @description 记录并设置state.tabs
   * @param newTabs
   */
  const recordAndSetTabs = (newTabs: Tabs) => {
    setTabs([...newTabs]);
    setStorage(PAGE_TABS, newTabs);
    actionRef.current.tabs = newTabs;
  };

  /**
   *
   * @description 父级触发更新tabs
   * @param type
   * @param name
   * @returns
   */
  const updateTabs: UpdateTabs = (type, name) => {
    const tabIndex = tabs.findIndex((item) => item.name === name);
    const { name: currentName, pathname: currentPathname } = tabs[tabIndex];
    switch (type) {
      case 'remove':
        tabs.splice(tabIndex, 1);
        recordAndSetTabs(tabs);
        if (currentName === activeKey) {
          // 关闭当前打开的标签
          updateTabs('change', tabs[0].name);
        }
        break;
      case 'change':
        history.push(currentPathname);
        break;

      default:
        break;
    }
    return { name: currentName, pathname: currentPathname };
  };

  useEffect(() => {
    const { title } =
      routesFormat.find((item: any) => `/f/${item.key}` === fixPathnameHasParent(pathname)) || {};
    if (!title) return;
    const { tabs: currentTabs } = actionRef.current;
    if (!currentTabs.find((item) => item.name === title)) {
      currentTabs.push({ name: title, pathname });
      recordAndSetTabs(currentTabs);
    }
    setActiveKey(title);
    dispatch({
      type: 'global/changePageTabs',
      payload: pathname,
    });
  }, [pathname]);
  return [tabs, activeKey, updateTabs];
}

export function usePageTabsChange(): [boolean] {
  const [show, setShow] = useState(false);
  const location = useLocation();
  const { pathname } = location;
  const { pathname: globalPathname } = useSelector((state: ConnectState) => state.global);
  useEffect(() => {
    setShow(pathname === globalPathname);
  }, [globalPathname]);
  return [show];
}
